<?php

namespace app\helper\ChannelSdk;

use app\aTrait\Single;
use app\model\ChannelSdkBind;
use app\model\User;
use Exception;
use Shopwwi\WebmanAuth\Facade\JWT as JwtFace;

class Official
{

    use Single;


    public function loginAuth($channel, $token): array
    {

        $state = true;

        try {
            $tokenInfo = JwtFace::verify($token);

            if (empty($tokenInfo)) {
                throw new Exception('请登录', 999);
            }
            if ($tokenInfo->iss !== config('plugin.shopwwi.auth.app.jwt.iss')) {
                throw new Exception('身份验证令牌无效', 999);
            }
            if ($tokenInfo->guard !== 'user') {
                throw new Exception('身份验证令牌无效', 999);
            }
            if ($tokenInfo->iat > time()) {
                throw new Exception('身份验证令牌无效', 999);
            }
            if ($tokenInfo->exp <= time()) {
                throw new Exception('身份验证令牌无效', 999);
            }

            // 登录用户验证
            $user = User::query()->where('ulid', $tokenInfo->extend->ulid)->where('state', 1)->first();
            if (!$user) {
                throw new Exception('请登录', 999);
            }
        } catch (Exception) {
            $state = false;
        }

        if ($state) {
            ChannelSdkBind::query()->create([
                'user' => $user['ulid'],
                'channel' => $channel,
                'channel_uid' => $user['ulid'],
                'channel_data' => json_encode([]),
            ]);
        }

        return [
            'state' => $state,
            'message' => $state ? '' : '登录失败',
            'data' => $state ? [
                'uid' => $user['ulid'],
            ] : [],
        ];

    }

}